/* 
Scenic Graphics Library
Copyright (C) 2007 Jouni Tulkki

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USApackage scenic;
*/

package scenic;

import java.awt.Rectangle;
import java.util.LinkedList;
import java.util.ListIterator;


class CacheImage {
	private Image cacheImage;
	private LinkedList<Rectangle> glyphList = new LinkedList<Rectangle>();
	private LinkedList<Rectangle> oldGlyphList = new LinkedList<Rectangle>();
	private int top;
	private int rowHeight;
	private int rowX;
	private int width;
	private int height;
	
	public CacheImage(Image image) {
		cacheImage = image;
		width = image.getWidth();
		height = image.getHeight();
	}
	
	public Image getCacheImage() {
		return cacheImage;
	}
	
	public Rectangle addImage(ImageInfo image) {
		int w = image.width;
		int h = image.height;
		
		if(cacheImage.getFormat() != image.format)
			return null;

		if(rowX + w > width)
		{
			top += rowHeight;
			rowHeight = 0;
			rowX = 0;
		}
		if(top + h > height)
		{
			if(h > height)
				return null;
			top = 0;
			rowX = 0;
			rowHeight = h;
			ListIterator itr = oldGlyphList.listIterator();
			
			while(itr.hasNext())
				((Rectangle)itr.next()).width = -1;
			oldGlyphList = glyphList;
			glyphList = new LinkedList<Rectangle>();
		}
		if(h > rowHeight)
			rowHeight = h;
		
		ListIterator itr = oldGlyphList.listIterator();
		while(itr.hasNext())
		{
			Rectangle r = (Rectangle)itr.next();
			
			if(r.y >= top + rowHeight)
				break;
			r.width = -1;
			itr.remove();
		}
		
		Rectangle r = new Rectangle(rowX, top, w, h);
		
		rowX += w;		
		glyphList.addLast(r);
		cacheImage.write(r.x, r.y, r.width, r.height, image.data, image.format);
		
		return r;
	}
}
